package com.yc.sole.framework.mybatis.config;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yc.sole.framework.context.SecureContextHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author yizuomin
 * @date 2022/4/16 09:08
 **/
@Configuration
public class MpMetaObjectHandler implements MetaObjectHandler {

    public static final String CREATE_TIME = "createTime";
    public static final String CREATE_USER_ID = "createUserId";
    public static final String UPDATE_TIME = "updateTime";
    public static final String UPDATE_USER_ID = "updateUserId";

    @Override
    public void insertFill(MetaObject metaObject) {
        // 0为系统用户
        Object userId = Objects.nonNull(SecureContextHolder.getUserId()) ? SecureContextHolder.getUserId() : 0;
        this.setFieldValByName(CREATE_USER_ID, userId, metaObject);
        this.setFieldValByName(CREATE_TIME, DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"), metaObject);
        this.setFieldValByName(UPDATE_USER_ID, userId, metaObject);
        this.setFieldValByName(UPDATE_TIME, DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 0为系统用户
        Object userId = Objects.nonNull(SecureContextHolder.getUserId()) ? SecureContextHolder.getUserId() : 0;
        this.setFieldValByName(UPDATE_TIME, DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"), metaObject);
        this.setFieldValByName(UPDATE_USER_ID, userId, metaObject);
    }
}
